package com.module.ad_gromore.ad;

import android.app.Activity;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.module.ad_gromore.LogADUtils;
import com.module.ad_gromore.manager.AdInterstitialFullManager;
import com.bytedance.msdk.adapter.util.Logger;
import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.reward.RewardItem;
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAdListener;
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAdLoadCallback;

import java.util.Map;
import java.util.Random;

/**
 * 插全屏广告，其中里面会含有半屏
 */
public class InterstitialFullAd {
    private static final String TAG = "广告";
    private AdInterstitialFullManager mAdInterstitialFullManager; //插全屏管理类
    private boolean mLoadSuccess = false;
    private String mAdUnitId;

    private static InterstitialFullAd interstitialAd;

    public static void loadAd(Activity context, final String mAdUnitId, boolean isShow) {
        loadAd(context, mAdUnitId, 0, isShow);
    }

    /**
     * @param context
     * @param mAdUnitId
     * @param maxRandom 最大随机数，随机到了才能显示，控制显示概率
     */
    public static void loadAd(Activity context, final String mAdUnitId, int maxRandom, boolean isShow) {
        if (!isShow) {
            return;
        }
        int randomNumber = new Random().nextInt(maxRandom + 1);
        LogADUtils.e(TAG, "随机数" + randomNumber);
        if (randomNumber != 0) {
            return;
        }
        interstitialAd = new InterstitialFullAd(mAdUnitId);
        interstitialAd.load(context);
        if (context instanceof FragmentActivity) {
            ((FragmentActivity) context).getLifecycle().addObserver(new DefaultLifecycleObserver() {

                @Override
                public void onStop(@NonNull LifecycleOwner owner) {
                    DefaultLifecycleObserver.super.onStop(owner);
                    //onStop 就要开始销毁
                    if (interstitialAd != null) {
                        interstitialAd.onDestroy();
                        interstitialAd = null;
                    }
                    ((FragmentActivity) context).getLifecycle().removeObserver(this);
                }

                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    DefaultLifecycleObserver.super.onDestroy(owner);
                    if (interstitialAd != null) {
                        interstitialAd.onDestroy();
                        interstitialAd = null;
                    }
                    ((FragmentActivity) context).getLifecycle().removeObserver(this);
                }
            });
        }
    }

    private InterstitialFullAd(String mAdUnitId) {
        this.mAdUnitId = mAdUnitId;
    }

    private void load(Activity context) {
        mAdInterstitialFullManager = new AdInterstitialFullManager(context, new GMInterstitialFullAdLoadCallback() {
            @Override
            public void onInterstitialFullLoadFail(@NonNull AdError adError) {
                mLoadSuccess = false;
                LogADUtils.e(TAG, "load interaction ad error : " + adError.code + ", " + adError.message);
                mAdInterstitialFullManager.printLoadFailAdnInfo();// 获取本次waterfall加载中，加载失败的adn错误信息。
            }

            @Override
            public void onInterstitialFullAdLoad() {
                mLoadSuccess = true;
                LogADUtils.e(TAG, "load interaction ad success ! ");
                mAdInterstitialFullManager.printLoadAdInfo(); //展示已经加载广告的信息
                mAdInterstitialFullManager.printLoadFailAdnInfo();// 获取本次waterfall加载中，加载失败的adn错误信息。
            }

            @Override
            public void onInterstitialFullCached() {
                mLoadSuccess = true;
                LogADUtils.d(TAG, "onFullVideoCached....缓存成功！");
                showInterFullAd(context);
            }
        });
        if (mAdInterstitialFullManager != null) {
            mAdInterstitialFullManager.loadAdWithCallback(mAdUnitId);
        }
    }

    /**
     * 展示广告
     */
    private void showInterFullAd(Activity context) {
        if (mLoadSuccess && mAdInterstitialFullManager != null) {
            if (mAdInterstitialFullManager.getGMInterstitialFullAd() != null && mAdInterstitialFullManager.getGMInterstitialFullAd().isReady()) {
                //在获取到广告后展示,强烈建议在onInterstitialFullCached回调后，展示广告，提升播放体验
                //该方法直接展示广告，如果展示失败了（如过期），会回调onVideoError()
                //展示广告，并传入广告展示的场景
                mAdInterstitialFullManager.getGMInterstitialFullAd().setAdInterstitialFullListener(mGMInterstitialFullAdListener);
                mAdInterstitialFullManager.getGMInterstitialFullAd().showAd(context);
                mAdInterstitialFullManager.printSHowAdInfo();//打印已经展示的广告信息
                mLoadSuccess = false;
            } else {
                LogADUtils.d(TAG, "当前广告不满足show的条件");
            }
        } else {
            LogADUtils.d(TAG, "请先加载广告");
        }
    }

    private GMInterstitialFullAdListener mGMInterstitialFullAdListener = new GMInterstitialFullAdListener() {
        @Override
        public void onInterstitialFullShow() {
            LogADUtils.d(TAG, "插全屏广告show");
        }

        /**
         * show失败回调。如果show时发现无可用广告（比如广告过期或者isReady=false），会触发该回调。
         * 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载。
         * @param adError showFail的具体原因
         */
        @Override
        public void onInterstitialFullShowFail(@NonNull AdError adError) {
            LogADUtils.d(TAG, "插全屏广告展示失败");

            // 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载

        }

        @Override
        public void onInterstitialFullClick() {
            LogADUtils.d(TAG, "插全屏广告click");
        }

        @Override
        public void onInterstitialFullClosed() {
            LogADUtils.d(TAG, "插全屏广告close");
        }

        @Override
        public void onVideoComplete() {
            LogADUtils.d(TAG, "插全屏播放完成");
        }

        @Override
        public void onVideoError() {
            LogADUtils.d(TAG, "插全屏播放出错");
        }

        @Override
        public void onSkippedVideo() {
            LogADUtils.d(TAG, "插全屏跳过");
        }

        /**
         * 当广告打开浮层时调用，如打开内置浏览器、内容展示浮层，一般发生在点击之后
         * 常常在onAdLeftApplication之前调用
         */
        @Override
        public void onAdOpened() {
            LogADUtils.d(TAG, "插全屏广告onAdOpened");
        }

        /**
         * 此方法会在用户点击打开其他应用（例如 Google Play）时
         * 于 onAdOpened() 之后调用，从而在后台运行当前应用。
         */
        @Override
        public void onAdLeftApplication() {
            LogADUtils.d(TAG, "onAdLeftApplication");
        }

        @Override
        public void onRewardVerify(@NonNull RewardItem rewardItem) {
            Map<String, Object> customData = rewardItem.getCustomData();
            if (customData != null) {
                String adnName = (String) customData.get(RewardItem.KEY_ADN_NAME);
                switch (adnName) {
                    case RewardItem.KEY_GDT:
                        Logger.d(TAG, "rewardItem gdt: " + customData.get(RewardItem.KEY_GDT_TRANS_ID));
                        break;
                }
            }
            LogADUtils.d(TAG, "onRewardVerify");
        }
    };

    public void onDestroy() {
        if (mAdInterstitialFullManager != null) {
            mAdInterstitialFullManager.destroy();
        }
    }
}
